package filter;

import com.sun.deploy.net.HttpRequest;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.3 下午 16:26
 */
@WebFilter("/*")
public class CharacterFilter implements Filter {

    public void init(FilterConfig config) throws ServletException {
        System.out.println("全局过滤器初始化了");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //浏览器发送请求资源文件的时候,需要将请求对象的信息携带服务器,
        //通过拦截器.获取请求方式
        String method = request.getMethod();

        if(method.equalsIgnoreCase("post")){
            //解决post中文乱码
            request.setCharacterEncoding("utf-8");
        }

        //解决响应的中文乱码
        response.setContentType("text/html;charset=utf-8");
        //放行
        chain.doFilter(req, resp);
    }
    public void destroy() {
        System.out.println("全局过滤器销毁了...");
    }

}
